package com.example.demo.tixiban;

/**
 * @author xujm
 * @version V2.4
 * @since 2.4.0 2022/2/13 12:41
 */
public class 位运算实现加减乘除 {

    /**
     *  (1) a 异或 b 可以看做无进位相加
     *  (2) a & b  << 1  可以看做进位的值
     *  (3) 如果 (a & b) >0 递归
     *
     * @param a
     * @param b
     * @return
     */
    public static int myAdd(int a,int b){
        int x = a ^ b;
        int y = (a & b) << 1;
        if(y != 0){
            return myAdd(x,y);
        }
        return x;
    }

    /**
     * 减法: a-b == a + b的相反数 == a + (~b+1)
     *   8 -4  == 1000 - 0100  == 1000 + ...1100 == 0(符号位) 00000100  == 4
     *   12 - 2 ==1100 - 0010 == 00001100 + 1111 1110 == (0)1010 == 10
     * @return
     */
    public static Integer minus(int a ,int b){
        return myAdd(a,myAdd(~b,1));
    }

    /**
     * 乘法
     *  result = 0
     *  a x b
     *  b的最后一位不等于0，那么 result + a
     *  a左移 1位
     *  b无符号右移 1位(有符号 死循环)
     * @param a
     * @param b
     * @return
     */
    public static int multic(int a,int b){
        int result = 0;
        while (b != 0){
            if((b & 1)!=0){
                result = myAdd(result,a);
            }
            a <<= 1;
            b >>>= 1;
        }
        return result;
    }

    //辗转相加

    public static int divide(int divided,int divisor){

        //系统最小值 无法取绝对值讨论处理
        if(divided == Integer.MIN_VALUE && divisor == Integer.MIN_VALUE){
            return 1;
        }else if (divisor == Integer.MIN_VALUE){
            return 0;
        }else if(divided == Integer.MIN_VALUE){
            if(divisor == -1){
                return Integer.MAX_VALUE;
            }else{
                int ans = div(myAdd(divided,1),divisor);
                return ans + div(minus(divided,ans * divisor),divisor);
            }
        }

        int a = divided;
        int b = divisor;
        int sign = 1;
        if(a >0 && b>0){
            sign = 1;
        }else if(a <0 && b<0){
            sign =1;
        }else{
            sign = -1;
        }
        a = a >0?a:-a;
        b = b >0?b:-b;

        int res = div(a,b);
        return sign > 0? res : -res;
    }

    /**
     *   定义累加次数 count = 1
     *  (1) a<b return 0;
     *  (2) 循环 a>b  b = b+b, count = count + count;
     *  (3) 循环结束: 多处理的一次退回去
     *
     * @param a
     * @param b
     * @return
     */
    public static int div(int a,int b){
        if(a < b) return 0;
        int count =1;
        int adder = b;
        while(a>=adder){
            count =count + count;
            adder = adder + adder;
        }
        count = count /2;
        adder = adder / 2;
        return count + div(a-adder,b);
    }


    public static void main(String[] args) {
        // System.out.println(myAdd(48,22));
        // System.out.println(multic(3,-7));
        System.out.println(divide(15,4));
    }





}
